package com.example.taobaounion.presenter.impl

import com.example.taobaounion.model.bean.Categories
import com.example.taobaounion.net.API
import com.example.taobaounion.presenter.IHomePresenter
import com.example.taobaounion.view.IHomeCallBack
import com.example.taobaounion.utils.RetrofitManager
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 *@author : Administrator
 *@descreption : HomeFragment的Presenter
 */
class HomePresenterImpl : IHomePresenter {
    var mIHomeCallBack: IHomeCallBack? = null

    override fun getCategories() {
        if (mIHomeCallBack != null) {
            mIHomeCallBack?.loading()
        }

        var request = RetrofitManager.getInstance().retrofit.create(API::class.java)
        val call = request.getCategories()
        call.enqueue(object : Callback<Categories> {
            override fun onFailure(call: Call<Categories>, t: Throwable) {
                if (mIHomeCallBack != null) {
                    mIHomeCallBack?.error()
                }
            }

            override fun onResponse(call: Call<Categories>, response: Response<Categories>) {
                val categories = response.body()
                if (mIHomeCallBack != null) {
                    if (categories?.data?.size == 0) {
                        mIHomeCallBack?.noData()
                    } else {
                        mIHomeCallBack?.loadCategories(categories)
                    }
                }
            }
        })


    }


    override fun registerCallBack(homeCallBack: IHomeCallBack) {
        this.mIHomeCallBack = homeCallBack
    }

    override fun unregisterCallBack() {
        if (mIHomeCallBack != null) {
            mIHomeCallBack = null
        }
    }
}